package com.sondon.mayi.fragment;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.annotation.SuppressLint;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sondon.mayi.activity.ChooseRegionActivity_;
import com.sondon.mayi.activity.LoginActivity_;
import com.sondon.mayi.activity.SetPasswdActivity_;
import com.sondon.mayi.activity.ShareActivity_;
import com.sondon.mayi.entity.ContactEntity;
import com.sondon.mayi.fruit.R;
import com.sondon.mayi.ui.Picture_PopupWindows;
import com.sondon.mayi.util.GsonUtil;
import com.sondon.mayi.util.LogUtil;
import com.sondon.mayi.util.MyPrefs_;
import com.sondon.mayi.util.ToastUtils;

@SuppressLint("HandlerLeak")
@EFragment(R.layout.configold)
public class ConfigFragmentPageOld extends BaseFragment {
	@ViewById
	LinearLayout upgrade_msg_box;// 升级会员
	@ViewById
	ImageView face;// 头像I
	@ViewById
	TextView mobile;// 手机号T
	@ViewById
	ImageView rank_pic;// 等级头像I
	@ViewById
	TextView rank;// 等级T
	@ViewById
	TextView upgrade;// 等级升级T
	@ViewById
	TextView you_not_login;// 没有登录T
	@ViewById
	LinearLayout version_box;// 版本号L
	@ViewById
	TextView version_name;// 版本T
	// @ViewById
	// ProgressBar waiting_verion;//版本进程P
	@ViewById
	LinearLayout upload_head_pic_box;// 上传头像L
	@ViewById
	LinearLayout modify_region_box;// 修改我的地区L
	@ViewById
	TextView region;// 地区T
	@ViewById
	LinearLayout upload_contact_box;// 上传更新通讯录L
	@ViewById
	LinearLayout addr_man;// 收货地址管理
	@ViewById
	LinearLayout passwd_box;// 密码设置
	@ViewById
	LinearLayout share;// 分享
	@ViewById
	TextView kfphone;// 客服电话
	@ViewById
	Button logout;// 登出

	private AsyncQueryHandler asyncQuery;
	private List<ContactEntity> contactList;
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	private static final int PICK_IMAGE_ACTIVITY_REQUEST_CODE = 200;

	@AfterViews
	public void initView() {
		// ToastUtils.show(getActivity(), R.string.processing);
		if (!myprefs.is_login().get()) {
			upgrade_msg_box.setVisibility(View.GONE);
			you_not_login.setVisibility(View.VISIBLE);
		} else {
			upgrade_msg_box.setVisibility(View.GONE);
			you_not_login.setVisibility(View.VISIBLE);
		}

		// 获取联系人
		asyncQuery = new MyAsyncQueryHandler(getActivity().getContentResolver());
		initContacts();
	
	}

	@Click({ R.id.logout, R.id.version_box, R.id.upload_head_pic_box,
			R.id.modify_region_box, R.id.upload_contact_box, R.id.addr_man,
			R.id.passwd_box, R.id.share, R.id.you_not_login })
	public void OnClick(View v) {
		switch (v.getId()) {
		case R.id.logout://登出
			myprefs.is_login().remove();
			break;
		case R.id.you_not_login://没有登录
			openActivity(LoginActivity_.class);
			break;
		case R.id.version_box://版本号
			ToastUtils.show(getActivity(), "目前已经是最新版本");
			break;
		case R.id.upload_head_pic_box://上传头像
			if (!myprefs.is_login().get()) {
				openActivity(LoginActivity_.class);
			} else {
				// 选择图片来源：相册或者照相机
//				new Picture_PopupWindows(ConfigFragmentPageOld.this, face);
			}
			break;
		case R.id.modify_region_box://选择地区
			openActivity(ChooseRegionActivity_.class);
			break;
		case R.id.upload_contact_box:// 上传通讯录
			ToastUtils.show(getActivity(), "上传成功");
			LogUtil.e(TAG, "联系人  ："+GsonUtil.ObjectToJson(contactList));
			break;
		case R.id.addr_man://添加收货地址
			break;
		case R.id.passwd_box://设置密码
			openActivity(SetPasswdActivity_.class);
			break;
		case R.id.share://分享
			openActivity(ShareActivity_.class);
			break;
		default:
			break;
		}
	}

	/******************************************************** 上传通讯录 **********************************************************/
	/**
	 * 
	 * @Author 蔡文锋
	 * @Data_Time 2015-6-12 下午2:41:37
	 * @Description { 初始化联系人查询 }
	 */
	private void initContacts() {
		// 联系人的Uri
		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		// 查询的列
		String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
				ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
				ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY };

		// 按照sort_key升序查询
		asyncQuery.startQuery(0, null, uri, projection, null, null,
				"sort_key COLLATE LOCALIZED asc");
	}

	/**
	 * 
	 * @Project : Fruit
	 * @Package : com.sondon.mayi.fragment
	 * @Class : ConfigFragmentPage.java
	 * @Author : 蔡文锋
	 * @DateTime：2015-6-12 下午4:35:24
	 * @Blog：http://blog.csdn.net/caiwenfeng_for_23
	 * @Description : {数据库异步查询类AsyncQueryHandler}
	 */
	private class MyAsyncQueryHandler extends AsyncQueryHandler {

		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
		}

		/**
		 * 查询结束的回调函数
		 */
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor != null && cursor.getCount() > 0) {

				contactList = new ArrayList<ContactEntity>();
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					ContactEntity cb = new ContactEntity();

					cursor.moveToPosition(i);
					String name = cursor.getString(1);
					String number = cursor.getString(2);
//					String sortKey = cursor.getString(3);
//					int contactId = cursor.getInt(4);
//					Long photoId = cursor.getLong(5);
//					String lookUpKey = cursor.getString(6);

					cb.setName(name);
					cb.setPhone(number);
//					cb.setSortKey(sortKey);
//					cb.setContactId(contactId);
//					cb.setPhotoId(photoId);
//					cb.setLookUpKey(lookUpKey);
					
					contactList.add(cb);
				}
			}
		}
	}

	/******************************************************* 拍照 相册 *************************************************************/

	private static String picFileFullName;

	// 拍照
	public void camera() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File outDir = Environment
					.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			if (!outDir.exists()) {
				outDir.mkdirs();
			}
			File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
			picFileFullName = outFile.getAbsolutePath();
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
			startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
		} else {
			Log.e(TAG, "请确认已经插入SD卡");
		}
	}

	// 打开本地相册
	public void openAlbum() {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_PICK);

		intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, PICK_IMAGE_ACTIVITY_REQUEST_CODE);

		// Intent intent = new Intent();
		// intent.setType("image/*");
		// intent.setAction(Intent.ACTION_GET_CONTENT);
		// this.startActivityForResult(intent,
		// PICK_IMAGE_ACTIVITY_REQUEST_CODE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == getActivity().RESULT_OK) {
				Log.e(TAG, "获取图片成功，path=" + picFileFullName);
				setImageView(picFileFullName);
			} else if (resultCode == getActivity().RESULT_CANCELED) {
				// 用户取消了图像捕获
			} else {
				// 图像捕获失败，提示用户
				Log.e(TAG, "拍照失败");
			}
		} else if (requestCode == PICK_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == getActivity().RESULT_OK) {
				Uri uri = data.getData();
				if (uri != null) {
					String realPath = getRealPathFromURI(uri);
					Log.e(TAG, "获取图片成功，path=" + realPath);
					setImageView(realPath);
				} else {
					Log.e(TAG, "从相册获取图片失败");
				}
			}
		}
	}

	private void setImageView(String realPath) {
		Bitmap bmp = BitmapFactory.decodeFile(realPath);
		int degree = readPictureDegree(realPath);
		if (degree <= 0) {
			face.setImageBitmap(bmp);
		} else {
			Log.e(TAG, "rotate:" + degree);
			// 创建操作图片是用的matrix对象
			Matrix matrix = new Matrix();
			// 旋转图片动作
			matrix.postRotate(degree);
			// 创建新图片
			Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0,
					bmp.getWidth(), bmp.getHeight(), matrix, true);
			face.setImageBitmap(resizedBitmap);
		}
	}

	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			// Do not call Cursor.close() on a cursor obtained using this
			// method,
			// because the activity will do that for you at the appropriate time
			Cursor cursor = getActivity().managedQuery(contentUri, proj, null,
					null, null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	/**
	 * 读取照片exif信息中的旋转角度<br/>
	 * http://www.eoeandroid.com/thread-196978-1-1.html
	 * 
	 * @param path
	 *            照片路径
	 * @return角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

}